<?php
/**
 * Created by PhpStorm.
 * User: wuchunyin
 * Date: 2018/11/8
 * Time: 13:36
 */

namespace app\index\controller;
use app\index\base_controller\BaseController;
use app\index\table\StockTable;
use think\Db;
use think\Exception;

class Stock extends BaseController{

    /**
     * page--基本信息
     */
    public function stockListPage(){
        return view('stock_list');
    }

    /**
     * action--获取信息
     */
    public function getStockList(){
        $limit = input('limit');
        $offset = input('offset');
        $sort = input('sort');
        $order = input('order');
        $sortStr = "$sort $order";
        if(empty($sort)){
            $sortStr = 'STOCK_NO desc';
        }

        $condition = StockTable::getSessionConditions();

        try{
            $listSql = StockTable::table()->where($condition)->order($sortStr)->limit($offset,$limit)->fetchSql()->select();
            $list = Db::query($listSql);
            $totalSql = StockTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            return ['rows'=>$list,'total'=>$total[0]['TP_COUNT']];
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * page--新增
     */
    public function addPage(){
        $config = StockTable::getConfigAdd();
        $data = null;
        $this->assign('config',$config);
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return view('stock_add');
    }

    /**
     * action 新增
     */
    public function add() {
        $data = input();
        try{
            StockTable::add($data);
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * action 删除
     */
    public function deleteAll(){
        $list = input('list');
        Db::startTrans();
        try{
            foreach ($list as $stockNo){
                StockTable::delete(['STOCK_NO'=>$stockNo]);
            }
            Db::commit();
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            Db::rollback();
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * page--编辑
     */
    public function editPage(){
        $stockNo = input('stockNo');
        $config = StockTable::getConfigEdit();
        $data = StockTable::get($stockNo);
        $this->assign('config',$config);
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return view('stock_edit');
    }

    /**
     * 编辑
     */
    public function edit() {
        $stockNo = input('STOCK_NO');
        $data = input();
        try{
            StockTable::update(['STOCK_NO'=>$stockNo],$data);
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * page--高级查询
     */
    public function searchPage(){
        $this->view->engine->layout('layout_popup');
        return view('stock_search');
    }

    /**
     * page 新增变动
     */
    public function addAlterPage(){
        $idStr = input('idList');
        $stockList = StockTable::table()->where([['STOCK_NO','in',$idStr]])->select();
        if(empty($stockList)){
            return '查询库存信息失败';
        }
        $this->assign('stockIds',$idStr);
        $this->assign('stockList',$stockList);
        $this->view->engine->layout('layout_popup');
        return view('stock_alter_add');
    }

    /**
     * action 新增变动
     */
    /**
     * 新增变动
     */
    public function addAlter(){
        $alterNum = input('ALTER_NUM/a');
        $stockNo = input('STOCK_NO/a');
        $alterRemark = input('ALTER_REMARK/a');

        Db::startTrans();
        try{
            $nowDate = date('Y-m-d H:i:s');
            $nowDate = Db::raw("to_date('$nowDate','yyyy-mm-dd hh24:mi:ss')");
            $alterDate = input('ALTER_DATE');
            $alterDate = Db::raw("to_date('$alterDate','yyyy-mm-dd hh24:mi:ss')");


            $dataAlter['ALTER_NO'] = self::getAlterNextId();
            $dataAlter['ALTER_DATE'] = $alterDate;
            $dataAlter['WORK_PERSON'] = input('WORK_PERSON');
            $dataAlter['PHONE'] = input('PHONE');
            $dataAlter['TOTAL_PRICE'] = input('TOTAL_PRICE');
            $dataAlter['ALTER_REASON'] = input('ALTER_REASON');
            $dataAlter['INPUT_USER_ID'] = Login::getUserId();
            $dataAlter['INPUT_TIME'] = $nowDate;


            Db::table('ASSETS_STOCK_ALTER')->insert($dataAlter);

            foreach ($alterNum as $key=>$value) {
                if ($value>=1) {
                    $stockRes = StockTable::table()->where(['STOCK_NO'=>$stockNo[$key]])->find();
                    if (empty($stockRes)) {
                        Db::rollback();
                        return json_encode(['code'=>'0','msg'=>'查询库存'.$stockNo[$key].'失败']);
                    }

                    $dataAlterItem['ALTER_ITEM_ID'] = self::getAlterItemNextId();
                    $dataAlterItem['STOCK_NO'] = $stockNo[$key];
                    $dataAlterItem['ALTER_NUM'] = $value;
                    $dataAlterItem['ALTER_NO'] = $dataAlter['ALTER_NO'];
                    $dataAlterItem['ALTER_REMARK'] = $alterRemark[$key];

                    Db::table('ASSETS_STOCK_ALTER_ITEM')->insert($dataAlterItem);

                    $dataStock['STOCK_NUM'] = $stockRes['STOCK_NUM'] - $value;
                    $dataStock['TOTAL_PRICE'] = $dataStock['STOCK_NUM'] * $stockRes['PRICE'];
                    StockTable::update(['STOCK_NO'=>$stockNo[$key]],$dataStock);
                }
            }

            Db::commit();
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            Db::rollback();
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    public static function getAlterNextId(){
        $year = date('Y');
        $numMaxRecord = Db::table('ASSETS_STOCK_ALTER')
            ->field('max(SUBSTR(ALTER_NO,5,4)) as NUM')
            ->where([['SUBSTR(ALTER_NO,1,4)','=',$year]])
            ->fetchSql(true)
            ->find();
        $numMaxRecord = Db::query($numMaxRecord);
        $num = $numMaxRecord[0]['NUM'];
        if ($num == NULL) {
            $num = 0;
        }
        $num++;
        return $year.sprintf("%04d", $num);
    }


    public static function getAlterItemNextId(){
        $year = date('Y');
        $numMaxRecord = Db::table('ASSETS_STOCK_ALTER_ITEM')
            ->field('max(SUBSTR(ALTER_ITEM_ID,5,4)) as NUM')
            ->where([['SUBSTR(ALTER_ITEM_ID,1,4)','=',$year]])
            ->fetchSql(true)
            ->find();
        $numMaxRecord = Db::query($numMaxRecord);
        $num = $numMaxRecord[0]['NUM'];
        if ($num == NULL) {
            $num = 0;
        }
        $num++;
        return $year.sprintf("%04d", $num);
    }

    /**
     * page--变动信息
     */
    public function stockAlterList(){
        return view('stock_alter_list');
    }


    /**
     * 打印
     */
    public function printPage() {
        $id = input('id');
        $data = StockTable::get($id);
        if(empty($data)){
            return '查询库存信息失败';
        }
        $config = StockTable::getConfigPrint();
        $this->assign('config',$config);
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return view('stock_print');
    }


    public function addConditionSession() {
        $condition = input();
        Login::setListConditionStock($condition);
        return json_encode(['code'=>'200']);
    }

    public function alterSearchPage() {
        $this->view->engine->layout('layout_popup');
        return view('stock_alter_search');
    }

    public function addSessionAlter() {
        $condition = input();
        Login::setListConditionStockAlter($condition);
        return json_encode(['code'=>'200']);
    }

    public function importPage() {
        $this->view->engine->layout('layout_popup');
        return view('import');
    }

    public function import() {
        $inputData = input('data');
        $postData = base64_decode($inputData);
        $list = json_decode($postData,true);
        $start = input('start');

        Db::startTrans();
        $fieldList = StockTable::STOCK_FIELD_LIST;
        $fieldCount = count($fieldList);
        foreach ($list as $key => $row) {
            $data = [];

            // 字段赋值
            $i = 0;
            foreach ($row as $key1=>$value) {
                $data[$fieldList[$i]] = $value;
                $i++;
                if ($i>=$fieldCount) {
                    break;
                }
            }

            try{
                StockTable::addImport($data);
            }
            catch (Exception $e){
                Db::rollback();
                return json_encode(['code'=>'0','msg'=>"第".($key + $start)."行数据写入出错",'data'=>$e->getMessage()]);
            }
        }

        Db::commit();
        return json_encode(['code'=>'200','msg'=>'导入成功']);
    }

    /**
     * 库存分类统计
     */
    public function stockTypeStatisticsPage() {
        return view('stock_type_statistics');
    }

    /**
     * 库存分类统计
     */
    public function getStockTypeStatisticsList() {
        $limit = input('limit');
        $offset = input('offset');
        $sort = input('sort');
        $order = input('order');
        $sortStr = "$sort $order";
        if(empty($sort)){
            $sortStr = 'STOCK_TYPE_ID ASC';
        }

        $condition = null;
//        $listCondition = Login::getListConditionStock();
//        if (!empty($listCondition['STOCK_NO'])) {
//            $value = $listCondition['STOCK_NO'];
//            $condition[] = ['STOCK_NO','like',"$value%"];
//        }

        try{
            $list = Db::table('V_ASSET_STOCK_STATISTICS')
                ->where($condition)
                ->order($sortStr)
                ->limit($offset,$limit)
                ->select();
            $total =  Db::table('V_ASSET_STOCK_STATISTICS')
                ->where($condition)
                ->count();
            return ['rows'=>$list,'total'=>$total];
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * page 库存变动单列表
     */
    public function stockAlterListPage() {
        return view('stock_alter_list');
    }

    /**
     * action 获取变动单列表
     */
    public function getStockAlterList(){
        $limit = input('limit');
        $offset = input('offset');
        $sort = input('sort');
        $order = input('order');
        $sortStr = "$sort $order";
        if(empty($sort)){
            $sortStr = 'ALTER_NO desc';
        }

        $condition = null;
        $listCondition = Login::getListConditionStockAlter();
        if (!empty($listCondition['ALTER_NO'])) {
            $value = $listCondition['ALTER_NO'];
            $condition[] = ['ALTER_NO','like',"$value%"];
        }

        if (!empty($listCondition['ALTER_DATE_START'])) {
            $value = Db::raw("to_date('{$listCondition['ALTER_DATE_START']}','yyyy-mm-dd')");
            $condition[] = ['ALTER_DATE','>=',$value];
        }
        if (!empty($listCondition['ALTER_DATE_END'])) {
            $value = Db::raw("to_date('{$listCondition['ALTER_DATE_END']}','yyyy-mm-dd')");
            $condition[] = ['ALTER_DATE','<=',$value];
        }

        if (!empty($listCondition['TOTAL_PRICE_START'])) {
            $value = $listCondition['TOTAL_PRICE_START'];
            $condition[] = ['TOTAL_PRICE','>=',$value];
        }
        if (!empty($listCondition['TOTAL_PRICE_END'])) {
            $value = $listCondition['TOTAL_PRICE_END'];
            $condition[] = ['TOTAL_PRICE','<=',$value];
        }

        try{
            $listSql = Db::table('V_ASSET_STOCK_ALTER')
                ->where($condition)
                ->order($sortStr)
                ->limit($offset,$limit)
                ->fetchSql()
                ->select();
            $list = Db::query($listSql);
            $totalSql = Db::table('V_ASSET_STOCK_ALTER')->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            return ['rows'=>$list,'total'=>$total[0]['TP_COUNT']];
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * page 库存变动单详情
     */
    public function alterDetailPage() {
        $alterNo = input('alterNo');
        $alterData = Db::table('V_ASSET_STOCK_ALTER')->where(['ALTER_NO'=>$alterNo])->find();
        $this->assign('alterData',$alterData);

        $alterItemList = Db::table('V_ASSET_STOCK_ALTER_ITEM')
            ->where(['ALTER_NO'=>$alterNo])
            ->select();
        $this->assign('alterItemList',$alterItemList);

        $this->view->engine->layout('layout_popup');
        return view('stock_alter_detail');
    }

    public function searchAlterPage() {
        $this->view->engine->layout('layout_popup');
        return view('stock_alter_search');
    }

    /**
     * action 添加变动单查询条件到session
     */
    public function addAlterSession() {
        $condition = input();
        Login::setListConditionStockAlter($condition);
        return json_encode(['code'=>'200']);
    }

    /**
     * action
     */
    public function stockListByType() {
        $stockTypeId = input('typeId');
        $condition['STOCK_TYPE_ID'] = $stockTypeId;
        Login::setListConditionStock($condition);
        $this->redirect('stockListPage');
        return;
    }

    /**
     * page 库存导出页面
     */
    public function exportExcelPage() {
        $condition = StockTable::getSessionConditions();

        try{
            $totalSql = StockTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            $total = $total[0]['TP_COUNT'];
            $this->assign('total',$total);

            $arr = $this->getDownLoadList($total);
            $this->assign('downList',$arr);

            $this->view->engine->layout('layout_popup');
            return view('export_excel');
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * action 导出Excel
     */
    public function exportExcel(){
        $sortStr = 'STOCK_NO desc';
        $start = input('start');
        $startL = $start-1;
        $end = input('end');
        $endL = $end-$start+1;

        $condition = StockTable::getSessionConditions();

        try{

            $listSql = StockTable::table()->where($condition)->limit($startL,$endL)->order($sortStr)->fetchSql()->select();
            $list = Db::query($listSql);
            StockTable::exportExcel($list,"库存$start-$end");
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }


}